package com.lutzyt.delivery.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lutzyt.delivery.bean.Address;
import com.lutzyt.delivery.bean.User;
import com.lutzyt.delivery.service.AddressService;
import com.lutzyt.delivery.service.AreaService;
import com.lutzyt.delivery.service.UserService;
import com.lutzyt.delivery.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * controller 控制器
 *
 * @author zyt
 * @date 2021-05-18
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController extends ActionController<UserService> {
  private UserService service;
  private AddressService addressService;
  private AreaService areaService;

  @GetMapping("/{id}")
  public Result<User> getById(@PathVariable Integer id) {
    final User bean = service.getById(id);
    return Result.success(bean);
  }

  @PutMapping("/{id}")
  public Result<Void> update(@RequestBody User bean) {
    log.info("更新菜单:{}", bean);
    service.update(bean);
    return Result.success();
  }

  @PostMapping("/page")
  public Result<Page<User>> page(Integer pageSize, Integer pageNum) {
    final Page<User> page = service.page(new Page<>(pageNum, pageSize));
    return Result.success(page);
  }

  @DeleteMapping("/{id}")
  public Result<Void> del(@PathVariable Integer id) {
    log.info("删除:{}", id);
    service.deleteById(id);
    return Result.success();
  }

  @DeleteMapping
  public Result<Void> del(@RequestParam("id") List<String> ids) {
    log.info("pl删除:{}", ids);
    service.deleteByIds(ids);
    return Result.success();
  }

  @PostMapping
  public Result<Void> insert(@RequestBody User bean) {
    log.info("添加菜单:{}", bean);
    service.insert(bean);
    return Result.success();
  }

  @GetMapping("/address")
  public Result<List<Address>> addressList(@SessionAttribute("userId") String userId){
    final List<Address> addressList = addressService.query().eq("customer_id", userId).eq("deleted", 0).list();
    for (Address address : addressList) {
      address.setCity(areaService.findById(address.getCityId()).getAreaname());
      address.setProvince(areaService.findById(address.getProvinceId()).getAreaname());
      address.setCounty(areaService.findById(address.getCountyId()).getAreaname());
      address.setDetail(address.getProvince()+"/"+address.getCity()+"/"+address.getCounty()+"/"+address.getDetail());
    }
    return Result.success(addressList);
  }

  @Autowired
  public void setService(UserService service) {
    this.service = service;
  }

  @Autowired
  public void setAreaService(AreaService areaService) {
    this.areaService = areaService;
  }

  @Autowired
  public void setAddressService(AddressService addressService) {
    this.addressService = addressService;
  }


}
    